<?php

namespace App\Handlers;

use App\Models\AdminUser;
use App\Models\Deposite;
use Dcat\Admin\Admin;
use Large\Zhengdada\Functions;
use App\Models\Withdrawal;


class Team
{

    /**
     * 模块通用，生成团队结构图  简单方法，没用递归
     * $account 用户帐号
     * $type 查询类型，是合并返回还是 只返回数据
     * @param $account 查询用户
     * @param $type    查询类型
     * @param $date    查询时间
     * @return false|string|void
     */
    public static function treeToData2($account, $type, $date)
    {
        $userAll = AdminUser::whereHas('roles', function ($q) {
            $q->where('id', 2);
        })->get()->toArray();
        $user    = AdminUser::with(['deposite'])->where('username', $account)->first();
        $path    = Functions::explodeString('/', request()->path());// 访问路径


        $data = [];
        $t1 = '';
        $t2 = '';
        // 下级数据
        if (!empty($date)) {
            list($t1, $t2) = explode('/', $date);
            $t1 = $t1 . ' 00:00:00';
            $t2 = $t2 . ' 23:59:59';
        }

        foreach ($user->childs as $k => $v) {
            // 计算自身下的所有会员的自购金额, 相加 成功团队金额
            $numPrice = self::GetTeamMember($userAll, $v->id, $date);
            // 自购金额 $deposite - $withdrawal
            $deposite   = $v->deposite()->whereIn('type', ['1', '2'])->when(!empty($date), function ($q) use ($t1, $t2) {
                $q->whereBetween('created_at', [$t1, $t2]);
            })->sum('usd_amount');
            $withdrawal = $v->withdrawal()->whereIn('amount_type', [3])
                ->whereIn('sp_status', [0, 2])->when(!empty($date), function ($q) use ($t1, $t2) {
                    $q->whereBetween('created_at', [$t1, $t2]);
                })->sum('usd_amount');


            $data[$k]['id']      = $v['id'];
            $data[$k]['pid']     = $v['tjr_id'];
            $data[$k]['account'] = $v['username'];
            if ($v->where('tjr_id', $v->id)->first()) {
                if ($path[0] == 'hdcrm') {
                    $data[$k]['lazy'] = true;
                } else {
                    $data[$k]['lazy'] = false;
                }
            }

            if ($v->users_leader_id == 0) {
                $level = trans('handlers.admin_user_ptyhxxxxx');
            } else {
                $level = $v->users_leader->leader;
            }

            $str1              = $level.'　'.trans('handlers.admin_user_zhxxxxxxx').'：'.$v->username.','.trans('handlers.admin_user_xmxxxxxxx').'：'.$v->name.
                '，'.trans('handlers.admin_user_yxxxxxxxx').'：'.$v->email.'，'.trans('handlers.admin_user_sjhxxxxxx').'：'.$v->phone.
                '，'.trans('handlers.admin_user_tdjexxxxx').'：'.number_format($numPrice, 2).
                '，'.trans('handlers.admin_user_zgjexxxxx').'：'.number_format($deposite - $withdrawal, 2).
                //'，团队业绩：'.number_format($v->yj_total,2).
                '&nbsp;&nbsp;<i  data-id="'.$v->id.'" class="fa fa-search-plus spanId"></i>';
            $data[$k]['title'] = $str1;

            if ($path[0] != 'hdcrm') {
                if (!self::isVerifyUserUp($v)) {// 不可查询下级的子目录
                    unset($data[$k]);
                }
            }
        }

        // 如果是 1 ，加上自身，不然不加
        if ($type == 1) {
            // 计算自身下的所有会员的自购金额, 相加 成功团队金额
            $numPrice = self::GetTeamMember($userAll, $user->id, $date);
            // 自购金额 $deposite - $withdrawal
            $deposite   = $user->deposite()->whereIn('type', ['1', '2'])->when(!empty($date), function ($q) use ($t1, $t2) {
                $q->whereBetween('created_at', [$t1, $t2]);
            })->sum('usd_amount');
            $withdrawal = $user->withdrawal()->whereIn('amount_type', [3])->when(!empty($date), function ($q) use ($t1, $t2) {
                $q->whereBetween('created_at', [$t1, $t2]);
            })->whereIn('sp_status', [0, 2])->sum('usd_amount');

            if ($user->users_leader_id == 0) {
                $level = trans('handlers.admin_user_ptyhxxxxx');
            } else {
                $level = $user->users_leader->leader;
            }
            $newUser['id']      = $user->id;
            $newUser['pid']     = $user->tjr_id;
            $newUser['account'] = $user->username;
            $newUser['spread']  = true;// 节点是否展开
            $str                = $level.'　'.trans('handlers.admin_user_zhxxxxxxx').'：'.$user->username.'，'.trans('handlers.admin_user_xmxxxxxxx').'：'.$user->name.
                '，'.trans('handlers.admin_user_yxxxxxxxx').'：'.$user->email.'，'.trans('handlers.admin_user_sjhxxxxxx').'：'.$user->phone.
                '，'.trans('handlers.admin_user_tdjexxxxx').'：'.number_format($numPrice, 2).
                '，'.trans('handlers.admin_user_zgjexxxxx').'：'.number_format($deposite - $withdrawal, 2).
                //'，团队业绩：'.number_format($user->yj_total,2).
                '&nbsp;&nbsp;<i  data-id="'.$user->id.'" class="fa fa-search-plus spanId"></i>';
            $newUser['title']   = $str;
            if ($data) {
                $newUser['children'] = $data;
            }
        } else {
            $newUser = $data;
        }
        return json_encode($newUser, JSON_UNESCAPED_UNICODE);
    }


    /**
     * 计算自身下的所有会员的自购金额
     * 团队金额
     * @param          $members
     * @param          $mid
     * @param          $times    传过来的时间
     * @param          $members  所有会员
     * @param          $mid      第一次执行时候的用户id
     * @param  string  $times
     * @return mixed
     */
    public static function GetTeamMember($members, $mid, $times = '')
    {
        $Teams = array($mid);//最终结果
        $mids  = array($mid);//第一次执行时候的用户id
        do {
            $othermids = array();
            $state     = false;
            foreach ($mids as $valueone) {
                foreach ($members as $key => $valuetwo) {
                    if ($valuetwo['tjr_id'] == $valueone) {
                        $Teams[]     = $valuetwo['id'];//找到我的下级立即添加到最终结果中
                        $othermids[] = $valuetwo['id'];//将我的下级id保存起来用来下轮循环他的下级
                        //array_splice($members,$key,1);//从所有会员中删除他
                        $state = true;
                    }
                }
            }
            $mids = $othermids; //foreach中找到的我的下级集合,用来下次循环
        } while ($state == true);

        $price      = Deposite::whereIn('type', [1, 2])->whereIn('user_id', $Teams);
        $withdrawal = Withdrawal::whereIn('amount_type', [3])->whereIn('sp_status', [0, 2])->whereIn('user_id', $Teams);

        //echo $price->sum('usd_amount') - $withdrawal->sum('usd_amount') .'__'. $withdrawal->sum('usd_amount').'<br>';
        if ($times) {
            list($t1, $t2) = explode('/', $times);
            $t1 = $t1 . ' 00:00:00';
            $t2 = $t2 . ' 23:59:59';
            $price->whereBetween('created_at', [$t1, $t2]);
            $withdrawal->whereBetween('created_at', [$t1, $t2]);
        }
        return $price->sum('usd_amount') - $withdrawal->sum('usd_amount');
    }



    // 自购金额流水

    /**
     * 查询自购金额流水 公式方法
     * $user 用户实例
     * $id 传入查询id
     */
    public static function getUserOrder($data)
    {
        if ($data->count() > 0) {
            $str = <<<EOT
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                        <tr>
                            <th>trans('handlers.admin_user_zhxxxxxxx').帐号</th>
                            <th>trans('handlers.admin_user_xmxxxxxxx').姓名</th>
                            <th>trans('handlers.admin_user_jexxxxxxx').金额</th>
                            <th>trans('handlers.admin_user_sjxxxxxxx').时间</th>
                        </tr>
                        </thead>
                        <tbody>
EOT;
            foreach ($data as $k => $v) {
                $str .= '<tr>';
                $str .= '<td>'.$v->admin_user->username.'</td>';
                $str .= '<td>'.$v->admin_user->name.'</td>';
                $str .= '<td>'.number_format($v->usd_amount, 2).'</td>';
                $str .= '<td>'.$v->created_at.'</td>';
                $str .= '</tr>';
            }
            $str .= <<<a
                        </tbody>
                     </table>
                 </div>
a;
            return $str;
        } else {

            return '';
        }
    }


    /***
     * 判断查询用是不是自身的下级
     * @param $user
     */
    public static function isVerifyUserUp($user)
    {
        if (!in_array($user->tjr_id, [Admin::user()->id]) && $user->id !== Admin::user()->id) {
            return false;
        }
        return true;
    }

}




